package org.example.report_forms.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.report_forms.pojo.User;
import org.springframework.util.ResourceUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName ExcelExportUtils
 * @Author liupanpan
 * @Date 2025/1/10
 * @Description
 */
public class ExcelExportUtils {
    public static Workbook writeToExcel(Object o,Workbook workbook,String imageUrl) throws IllegalAccessException, IOException {
        //将对象转换为map，方便存取
        Map<String, Object> mapUtils = toMapUtils(o);
        //读取工作表
        Sheet sheet = workbook.getSheetAt(0);
        Row row=null;
        Cell cell=null;
        for (int i = 0; i < 100; i++) {
            row = sheet.getRow(i);
            if(row==null){break;}
            for (int j = 0; j < 100; j++) {
                cell = row.getCell(j);
                if (cell != null) {
                    //匹配
                    //获取单元格类型
                    if (cell.getCellType() == CellType.FORMULA) {
                        break;
                    } else {
                        String cellValue = cell.getStringCellValue();
                        if (StringUtils.isNotBlank(cellValue)) {
                            for (String key : mapUtils.keySet()) {
                                if (key.equals(cellValue)) {
                                    cell.setCellValue(mapUtils.get(key).toString());
                                }
                            }
                        }
                    }
                }
            }
        }
        //处理图片
        /*
        * 创建字节输出流
        * 读取图片，放入缓冲区中
        * 将图片写入字节输出流中
        * 控制图片写入，指定图片位置
        * */
        if (imageUrl !=null && !imageUrl.isEmpty()) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            BufferedImage read = ImageIO.read(new File(imageUrl));
            //获取图片后缀
            String type = imageUrl.substring(imageUrl.lastIndexOf(".")+1).toUpperCase();

            ImageIO.write(read, type, os);

            Drawing<?> patriarch = sheet.createDrawingPatriarch();
            Sheet sheet1 = workbook.getSheetAt(1);
            double value1 = sheet1.getRow(0).getCell(0).getNumericCellValue();
            double value2 = sheet1.getRow(0).getCell(1).getNumericCellValue();
            double value3 = sheet1.getRow(0).getCell(2).getNumericCellValue();
            double value4 = sheet1.getRow(0).getCell(3).getNumericCellValue();
            XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (int) value1, (int) value2, (int) value3, (int) value4);
            int format = 0;
            switch (type) {
                case "JPEG":
                    format = XSSFWorkbook.PICTURE_TYPE_JPEG;
                case "JPG":
                    format = XSSFWorkbook.PICTURE_TYPE_JPEG;
                case "PNG":
                    format = XSSFWorkbook.PICTURE_TYPE_PNG;
            }
            //把图片写入sheet指定位置
            patriarch.createPicture(anchor, workbook.addPicture(os.toByteArray(),format));
        }


        return workbook;
    }
    /*将对象转换为map集合,键为字段名，值为字段值*/
    public static Map<String,Object> toMapUtils(Object obj) throws IllegalAccessException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取对象的类
        Class<?> objClass = obj.getClass();
        HashMap<String, Object> map = new HashMap<>();

        //获取所有字段
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);//设置可访问性
            try {
                Object value = field.get(obj);
                if (value instanceof Date) {
                    value = sdf.format(value); // 转换日期为字符串
                }
                map.put(field.getName(), value);
            } catch (IllegalAccessException e) {
                e.printStackTrace(); // 处理异常
            }
        }
        return map;
    }
}
